package it.unisa.udocs.gestioneAutenticazione;

import it.unisa.udocs.commons.XMLParser;
import it.unisa.udocs.data.Account;
import it.unisa.udocs.facade.FacadeAutenticazione;
import it.unisa.udocs.facade.IFacadeAutenticazione;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom2.Document;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

/**
 * Servlet implementation class IsAnAccountServlet
 */
@WebServlet("/IsAnAccountServlet")
public class IsAnAccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IsAnAccountServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		IFacadeAutenticazione facAut= new FacadeAutenticazione();
		
		
		String user = request.getParameter("usr");
		String psw = request.getParameter("psw");
		
		Account acc = new Account(0, user, psw, "");
		
		int esiste = facAut.isAnAccount(acc); // se il metodo restituisce 0 l'account NON ESISTE
		if(esiste == 0 ) {
			System.out.println("Account Inesistente ");
			Document doc = XMLParser.notAnAccount(0);
    		
	    	// risponde al client
	    	XMLOutputter xml_out = new XMLOutputter();
	    	xml_out.setFormat(Format.getPrettyFormat());
	    	response.setContentType("text/xml");
	    	response.setHeader("Cache-Control",	"no-store, no-cache, must-revalidate");     
	    	PrintWriter out = response.getWriter(); 
	    	
	    	xml_out.output(doc, out);
		} else System.out.println("ACCOUNT ESISTENTE");
		
		
		
	}

}
